package cn.tjie.user.service.impl;

import cn.tjie.basic.exception.BusinessException;
import cn.tjie.basic.util.Md5Utils;
import cn.tjie.basic.util.StrUtils;
import cn.tjie.user.domain.Logininfo;
import cn.tjie.user.domain.User;
import cn.tjie.user.dto.EmailDto;
import cn.tjie.user.dto.UserDto;
import cn.tjie.user.mapper.LogininfoMapper;
import cn.tjie.user.mapper.UserMapper;
import cn.tjie.user.service.IUserService;
import cn.tjie.basic.service.impl.BaseServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * 业务实现类：
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService {


        @Autowired
        private RedisTemplate redisTemplate;
        @Autowired
        private LogininfoMapper logininfoMapper;
        @Autowired
        private UserMapper userMapper;

        @Override
        public void phoneRegister(UserDto userDto) {
            System.out.println(userDto);
            String phone = userDto.getPhone();
            String inputPhoneCode = userDto.getPhoneCode();
            String password = userDto.getPassword();
            String passwordRepeat = userDto.getPasswordRepeat();
            //一：校验：空值校验
           if(StringUtils.isEmpty(phone)||StringUtils.isEmpty(inputPhoneCode)||StringUtils.isEmpty(password)
           ||StringUtils.isEmpty(passwordRepeat)){
               throw new BusinessException("信息不能为空");
           }

            //二：校验：密码是否一致
            if(!password.equals(passwordRepeat)){
                throw new BusinessException("密码不一致！！！");
            }
            //三：手机验证码：是否过期，是否正确
            Object code = redisTemplate.opsForValue().get("register:" + phone);
            if(code==null){
                throw new BusinessException("验证码过期！！！");
            }
            String redisCode = code.toString().split(":")[0];
            if(!redisCode.equals(inputPhoneCode)){
                throw new BusinessException("验证码不正确！！！");
            }

            //四：添加到数据库
            //User user = userDto2User(userDto);
            //Logininfo logininfo = user2Logininfo(user);
            //保存到logininfo
            Logininfo logininfo = new Logininfo();
            logininfo.setPhone(phone);
            String salt = StrUtils.getComplexRandomString(32);
            String byMd5 = Md5Utils.encrypByMd5(password + salt);
            logininfo.setPassword(byMd5);
            logininfo.setSalt(salt);
            logininfo.setType(1);
            logininfoMapper.save(logininfo);
            //保存到user
            User user = new User();
            BeanUtils.copyProperties(logininfo,user);
            //设置LogininfoId，
            user.setLogininfoId(logininfo.getId());
            userMapper.save(user);
        }

    @Override
    public void emailRegister(EmailDto emailDto) {
        //1,校验邮箱和密码是否为空
        if(StringUtils.isEmpty(emailDto.getEmail())||StringUtils.isEmpty(emailDto.getPassword())||StringUtils.isEmpty(emailDto.getPasswordRepeat())){
            throw new BusinessException("注册信息不能为空");
        }
        //2.校验密码是否一致
        if(!emailDto.getPassword().equals(emailDto.getPasswordRepeat())){
            throw new BusinessException("两次密码输入不一致，请重新输入");
        }

        //3.添加
        Logininfo logininfo = new Logininfo();
        logininfo.setEmail(emailDto.getEmail());
        //生成盐值
        String salt = StrUtils.getComplexRandomString(32);
        logininfo.setSalt(salt);
        //拼接成password
        String byMd5 = Md5Utils.encrypByMd5(emailDto.getPassword() + salt);
        logininfo.setPassword(byMd5);
        //设置type等于1
        logininfo.setType(1);
        //添加
        logininfoMapper.save(logininfo);

        //添加到user
        User user = new User();
        BeanUtils.copyProperties(logininfo,user);
        user.setLogininfoId(logininfo.getId());
        userMapper.save(user);
    }

    private Logininfo user2Logininfo(User user) {
            Logininfo logininfo = new Logininfo();
            //按照属性同名原则进行属性拷贝【username，email，phone，salt，password】
            BeanUtils.copyProperties(user,logininfo); //底层原理就是通过getter,setter方法实现
            logininfo.setType(1);//用户手机验证码注册
            logininfo.setDisable(true);//手机验证码注册成功就可以直接使用
            return logininfo;
        }

        private User userDto2User(UserDto userDto) { //phone ,password
            User user = new User();
            user.setUsername(userDto.getPhone());
            user.setPhone(userDto.getPhone());
            //生成随机盐值
            String salt = StrUtils.getComplexRandomString(32);
            //用MD5加密加盐
            String md5Pwd = Md5Utils.encrypByMd5(userDto.getPassword() + salt);
            user.setSalt(salt);
            user.setPassword(md5Pwd);
            user.setState(1);
            return user;
        }

    @Override
    public void save(User user) {
        //处理盐值和密码
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = Md5Utils.encrypByMd5(user.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);

        //先添加logininfo
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);
        logininfo.setDisable(true);
        logininfoMapper.save(logininfo);//获取到自增ID

        //添加user的数据
        user.setLogininfoId(logininfo.getId());
        super.save(user);
    }

    @Override
    public void del(Long id) {
        //先查询登陆信息id
        User user = userMapper.loadById(id);

        //删除user
        super.del(id);

        //删除logininfo
        logininfoMapper.del(user.getLogininfoId());
    }

    @Override
    public void update(User user) {
        //处理盐值和密码
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = Md5Utils.encrypByMd5(user.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);

        User oldUser = userMapper.loadById(user.getId());//loginfo_id

        //修改user信息
        user.setLogininfoId(oldUser.getLogininfoId());
        super.update(user);

        //修改登陆信息
        Logininfo oldLogininfo = logininfoMapper.loadById(oldUser.getLogininfoId());
        BeanUtils.copyProperties(user,oldLogininfo);
        //设置会以前的id - 进行修改
        oldLogininfo.setId(oldUser.getLogininfoId());
        logininfoMapper.update(oldLogininfo);
    }
}

